package com.weilive.api.script;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.weilive.api.ServerConfig;

@Service
public class JsScriptSystem {
	private static final Logger logger = LoggerFactory.getLogger(JsScriptSystem.class);

	private static final Map<String, Invocable> SCRIPTFILE = new ConcurrentHashMap<String, Invocable>();

	public Object jsRunFun(String scriptFile, String funcName, Object[] inparams) {
		// String jspath = FileUtils.getResourcePath("resource/javascript/" +
		// scriptFile);
		String jspath = ServerConfig.getScriptPath() + scriptFile;
		return callJsFunc(jspath, funcName, inparams);
	}

	private Object callJsFunc(String scriptFile, String funcName, Object[] inparams) {
		try {
			Invocable invocableEngine = (Invocable) SCRIPTFILE.get(scriptFile);
			if (invocableEngine == null) {
				ScriptEngine jsEngine = new ScriptEngineManager().getEngineByName("JavaScript");

				InputStream in = new FileInputStream(scriptFile);
				try {
					jsEngine.eval(new BufferedReader(new InputStreamReader(in, "utf-8")));

					invocableEngine = (Invocable) jsEngine;
					SCRIPTFILE.put(scriptFile, invocableEngine);
				} finally {
					in.close();
				}
			}
			return invocableEngine.invokeFunction(funcName, inparams);
		} catch (Exception e) {
			logger.error("运行Js脚本出现错误,e={},js={}", new Object[] { e, scriptFile });
		}
		return null;
	}

	public void reloadAllScript() {
		logger.warn("Reload all js script on {}", new Date());
		SCRIPTFILE.clear();
	}

	public void reloadScript(String scriptName) {
		String jspath = ServerConfig.getScriptPath() + scriptName;
		logger.warn("Reload js script:{} on {}", jspath, new Date());
		SCRIPTFILE.remove(jspath);
	}
}
